package io.task.cc.message.socket.spi.client;

import io.task.cc.message.socket.thread.pool.SynchronousTask;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executor;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;

@Slf4j
@Setter
@Getter
public class ReconnRunnable extends SynchronousTask {

    ClientChannelContext clientChannelContext = null;
    Client client = null;


    public ReconnRunnable(ClientChannelContext clientChannelContext, Client client, Executor executor) {
        super(executor);
        this.clientChannelContext = clientChannelContext;
        this.client = client;
    }

    @Override
    public boolean isNeededExecute() {
        return false;
    }

    @Override
    public void runTask() {
        clientChannelContext.getReconnCount().incrementAndGet();
        ReentrantReadWriteLock closeLock = clientChannelContext.closeLock;
        WriteLock writeLock = closeLock.writeLock();
        writeLock.lock();
        try {
            if (!clientChannelContext.isClosed) //已经连上了，不需要再重连了
            {
                return;
            }
            long start = System.currentTimeMillis();
            client.reconnect(clientChannelContext, 2);
            long end = System.currentTimeMillis();
            long iv = end - start;


            log.error("{}, 第{}次重连,重连耗时:{} ms", clientChannelContext, clientChannelContext.getReconnCount(), iv);


        } catch (java.lang.Throwable e) {
            log.error(e.toString(), e);
        } finally {
            writeLock.unlock();
        }

    }
}
